<?php
/**
 * 基础函数库
 * 
 * @authors yutent (yutent@doui.cc)
 * @date    2014-08-31 17:36:52
 *
 */
function __autoload($class){

    $name = $class === 'D' ? $class : (strpos($class, 'Do_') === 0 ? substr($class, 3) : strtolower($class));

    $try1 = CORE . 'lib/' . $name . '.class.php';
    $try2 = CORE . 'extends/' . $name . '.class.php';
    $try3 = APPS . $name . '/controller/index.c.php';
    
    if(require_cache($try1) || require_cache($try2) || require_cache($try3)){
        return;
    }

    D::log($class . '类加载失败');
    _404();
}

/**
 * 优化的require_once
 * @param string $file 文件地址
 * @return boolean
 */
function require_cache($file) {
    static $imported = [];
    if (!isset($imported[$file])) {
        if (is_file($file)) {
            require $file;
            $imported[$file] = true;
        } else {
            $imported[$file] = false;
        }
    }
    return $imported[$file];
}



/**
 * [cookie cookie操作函数，最多可以有3个参数，只有1个参数时为读取cookie，采用jQuery风格]
 * @param  string $name [cookie名，必填]
 * @param  string $val [val值，为空时，删除cookie，不为空时，设置cookie]
 */
function cookie($name = ''){
    global $_G;
    if(empty($name)) return;
    $nums = func_num_args();
    $args = func_get_args();

    $data = [
        'path' => '/',
        'domain' => $_G['domain'],
        'expires' => time() + 3600 * 24 * 30,
        'secure' => FALSE,
        'httponly' => FALSE,
    ];

    if($nums == 1){
        return isset($_COOKIE[$name]) ? $_COOKIE[$name] : '';
    }elseif($nums == 2){
        if(empty($args[1])){
            $data['expires'] = time() -1;
        }
        setcookie($name, $args[1], $data['expires'], $data['path'], $data['domain']);
        return;
    }elseif($nums == 3){
        $list = $args[2];
        foreach ($data as $k => $val) {
            if(isset($list[$k]) && !empty($list[$k])){
                if($k == 'expires'){
                    $data[$k] = time() + 3600 * 24 * $list[$k];
                }else{
                    $data[$k] = $list[$k];
                }
            }
        }
        if(empty($args[1])){
            $data['expires'] = time() -1;
        }
        setcookie($name, $args[1], $data['expires'], $data['path'], $data['domain'], $data['secure'], $data['httponly']);
    } 
}


/**
 * 时间转化函数
 *
 * @param $now
 * @param $timestamp
 * @param $format
 * @return string
 */
function time_format($timestamp = '', $format = 'Y-m-d H:i:s') {

    $timestamp = empty($timestamp) ? time() : $timestamp;

    return gmdate($format, $timestamp + 8 * 3600);
    
}





function _404(){
    header('http/1.1 404 Not Founded');
    require_cache(ROOT . 'data/template/404.tpl');
    exit;
}

function _403(){

}

